package edu.jhu.secondhome.servlet;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import edu.jhu.secondhome.database.accessors.UserAccessor;
import edu.jhu.secondhome.database.beans.User;

public class LoginServlet extends HttpServlet
{
  /**
   * 
   */
  private static final long serialVersionUID = 6865293442603761077L;

  public void init() throws ServletException
  {

  }

  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException
  {
    processRequest(req, resp);
  }

  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException
  {
    processRequest(req, resp);
  }

  public void processRequest(HttpServletRequest request,
      HttpServletResponse response) throws ServletException, IOException
  {
    response.setContentType("text/html;charset=UTF-8");
    ServletContext servletContext = getServletContext();
    HttpSession session = request.getSession();

    ArrayList<String> errors = new ArrayList<String>();
    request.setAttribute("errors", errors);

    String login_email = request.getParameter("login_email");
    String login_password = request.getParameter("login_password");

    try
    {
      UserAccessor userDb = new UserAccessor();
      User user = userDb.getUserByEmail( login_email );

      if ( user == null )
      {
        errors.add( "Unable to login with this e-mail/password combo.  Please try again." );
        log("Null user from user table for email=" + login_email);
      }
      else
      {
        byte[] encryptedLoginPass = User.encryptString( login_password );
        String encryptedLoginPassStr = new String( encryptedLoginPass, "UTF-8" );

        String userUTF8 = new String( user.getPassword().getBytes(), "UTF-8" );
        String encryptedUTF8 = new String( encryptedLoginPassStr.getBytes(), "UTF-8" );
        
        // Success
        if ( userUTF8.equals(encryptedUTF8) )
        {
          // clear values to not carry over...
          user.setPassword("");
          user.setCreditCardNum("");
          user.setCreditCardExpMonth("");
          user.setCreditCardExpYear("");
          user.setCreditCardSecCode("");
          user.setBillingAddress("");
          user.setCurrentAddress("");
          user.setPhoneNumber("");
          session.setAttribute( "user", user );
          request.setAttribute("message", "Welcome, " + user.getFirstName() + "!" );
          
          String from = request.getParameter( "from" );
          if ( from != null && !from.equals( "" ) )
          {
            String checkin = request.getParameter( "check-in" );
            if ( checkin != null && !checkin.equals( "" ) )
            {
              request.setAttribute( "check-in", checkin );
            }
            
            String hotelName = request.getParameter( "hotelName" );
            if ( hotelName != null && !hotelName.equals( "" ) )
            {
              request.setAttribute( "hotelName", hotelName );
            }

            String numDays = request.getParameter( "numDays" );
            if ( numDays != null && !numDays.equals( "" ) )
            {
              request.setAttribute( "numDays", numDays );
            }

            String numPeople = request.getParameter( "numPeople" );
            if ( numPeople != null && !numPeople.equals( "" ) )
            {
              request.setAttribute( "numPeople", numPeople );
            }
            
            RequestDispatcher dispatcher = servletContext.getRequestDispatcher( from );
            dispatcher.forward(request, response);
            return;
          }

          RequestDispatcher dispatcher = servletContext.getRequestDispatcher("/index.jsp");
          dispatcher.forward(request, response);
          return;
        }
        else
        {
          errors.add( "Unable to login with this e-mail/password combo.  Please try again." );
        }
      }
    } catch (SQLException e)
    {
      // TODO Auto-generated catch block
      e.printStackTrace();
      errors.add(e.getMessage());
    } catch (NoSuchAlgorithmException e)
    {
      // TODO Auto-generated catch block
      e.printStackTrace();
      errors.add(e.getMessage());
    }
    
    RequestDispatcher dispatcher = servletContext.getRequestDispatcher("/index.jsp");
    dispatcher.forward(request, response);
    return;
  }
}
